package com.dongdongshop.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.dongdongshop.enums.ResultEnums;
import com.dongdongshop.uitl.JwtUtil;
import com.dongdongshop.vo.SeckillGoodsVO;
import com.dongdongshop.data.Result;
import com.dongdongshop.service.SeckillService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("seckill")
public class SeckillController extends BaseController{

    @Autowired
    private SeckillService seckillService;

    @Autowired
    private JwtUtil jwtUtil;

    //秒杀预热
    @PostMapping("cachePreHot")
    public Result cachePreHot(){
        seckillService.cachePreHot();
        return Result.OK();
    }

    //查询秒杀列表数据
    @GetMapping("seckillList")
    @SentinelResource(value = "seckillList",blockHandler = "hotBlockHandler")
    public Result seckillList(){
        List<SeckillGoodsVO> seckillGoodsVOList = seckillService.seckillList();
        return Result.OK().setData(seckillGoodsVOList);
    }

    //根据id查询秒杀商品
    @GetMapping("seckillGoods")  //对这个接口限流
    public Result seckillGoods(@RequestParam Long id){
        SeckillGoodsVO seckillGoodsVO = seckillService.seckillGoods(id);
        return Result.OK().setData(seckillGoodsVO);
    }
    //根据id查询秒杀商品
    @GetMapping("seckillGoodsById")
    public Result seckillGoodsById(@RequestParam Long id){
        SeckillGoodsVO seckillGoodsVO = seckillService.seckillGoods(id);
        return Result.OK().setData(seckillGoodsVO);
    }

    //获取明星的个人信息
    @PostMapping("getSuperStar")
    @SentinelResource(value = "getSuperStar")   //热点数据限流必须加上sentinelResource
    public Result getSuperStar(String starName){
        return Result.OK().setData(starName);
    }

    //秒杀的立即抢购
    @PostMapping("submitOrder")
    public Result submitOrder(@RequestHeader String AutharizeToken,@RequestParam Long id){
        //解析token
        Claims claims = jwtUtil.parseJwt(AutharizeToken);
        if (claims==null){   //用户没有登录
            return Result.response(ResultEnums.INEFFECTIVE);
        }
        String userId = claims.getId();
        try {
            seckillService.submitOrder(userId,id);
        }catch (Exception e){
            return Result.ER().setData(e.getMessage());
        }

        return Result.OK();
    }

}
